package org.xenon.vote.util.mail;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.xenon.vote.config.MailConfig;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Component
public class MailSender {

    @Async
    public void taskQQ(MailConfig cfg, org.xenon.vote.model.pojo.vo.Mail mail) {
        String to = mail.getRecv();
        String from = cfg.getQq_sender();
        String host = cfg.getQq_host();
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(cfg.getQq_sender(), cfg.getQq_passwd()); }});
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(from));
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        try {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        try {
            message.setSubject(mail.getTitle());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        try {
            message.setText(mail.getBody());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        try {
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
